package demo523;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;

public class DeleteDemo {
    private static final String URL = "jdbc:mysql://localhost:3306/userdb";
    private static final String DB_USERNAME = "root";
    private static final String DB_PASSWORD = "123456";

    /**
     * 删除功能:
     */
    public static void main(String[] args) {
        try {
            // 2. 注册（加载）驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 3. 获取数据库连接
            try (Connection connection = DriverManager.getConnection(URL, DB_USERNAME, DB_PASSWORD)) {

                // 4. 编写SQL语句
                String sql = "DELETE FROM userS WHERE id = ?";

                // 5. 执行SQL语句
                try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

                    // 5.1 给问号赋值
                    Scanner scanner = new Scanner(System.in);
                    System.out.println("请输入ID：");
                    int id = scanner.nextInt();

                    preparedStatement.setInt(1, id);

                    // 6. 执行删除操作
                    int i = preparedStatement.executeUpdate();

                    if (i > 0) {
                        System.out.println("删除成功");
                    } else {
                        System.out.println("删除失败");
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


